package com.drought.rained.business;

import android.app.Dialog;

import com.drought.rained.view.UpdateVersionDialogLJ;

import java.util.Stack;

public class DialogManagerLJ {
    private Stack<Dialog> dialogStack;
    private static DialogManagerLJ instance;

    private int updateVersionWeight = 1;
    private int normalWeight = 0;

    public static DialogManagerLJ getManager() {
        if (instance == null) {
            instance = new DialogManagerLJ();
        }

        return instance;
    }

    /**
     * 添加dialog
     * @param dialog
     */
    public void showDialogStack(Dialog dialog) {
        if (dialogStack == null) {
            dialogStack = new Stack<Dialog>();
        }

        if (dialogStack.empty()) {
            dialog.show();
            dialogStack.add(dialog);
        } else if (getDialogWeight(dialog) > getDialogWeight(currentDialog())){
            currentDialog().dismiss();
            dialog.show();
            dialogStack.add(0, dialog);
        } else {
            dialogStack.add(dialog);
        }
    }

    /**
     * 获取当前的dialog
     */
    public Dialog currentDialog() {
        return dialogStack.empty() ? null : dialogStack.lastElement();
    }

    public void dismissDialog(Dialog dialog) {
        if (dialog != null) {
            dialogStack.remove(dialog);
            dialog.dismiss();
            if (!dialogStack.empty()) {
                if(null!=currentDialog().getOwnerActivity()&&!currentDialog().getOwnerActivity().isFinishing()){
                    currentDialog().show();
                }
            }
        }
    }

    public void dismissDialog() {
        Dialog dialog = dialogStack.lastElement();
        dismissDialog(dialog);
    }

    public void dismissAllDialog() {
        for (Dialog dialog : dialogStack) {
            if (null != dialog) {
                dismissDialog(dialog);
            }
        }
    }

    /**
     * 获取对话框权重
     */
    public int getDialogWeight(Dialog dialog) {

        if (dialog instanceof UpdateVersionDialogLJ) {
            return updateVersionWeight;
        }
        return normalWeight;
    }

}
